package com.crawler.search.index.service.impl;

import cn.hutool.core.exceptions.ExceptionUtil;
import com.alibaba.fastjson.JSONObject;
import com.crawler.search.constant.CommonColumn;
import com.crawler.search.index.builder.DocSaverBuilder;
import com.crawler.search.index.service.ESDocSaver;
import com.crawler.search.utils.ESBulkProcessor;
import com.crawler.search.utils.ESIndexUtils;
import com.crawler.search.utils.IdGen;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.action.bulk.BulkProcessor;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.get.GetRequest;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.rest.RestStatus;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


/**
 *
 * ES操作Document数据实现（增删改）
 * @Class Name ESSaverImpl
 * @author zhangyonghui
 * @Create In 下午3:50:26
 */
@Service("esDocSaver")
public class ESDocSaverImpl implements ESDocSaver {

	protected static Logger logger = LoggerFactory.getLogger(ESDocSaverImpl.class);

	@Autowired
	public RestHighLevelClient client;

	@Autowired
	public ESIndexUtils esIndexUtils;

	@Autowired
	public ESBulkProcessor esBulkProcessor;


	/**
	 * 索引数据插入
	 * @param docSaverBuilder
	 */
	@Override
	public boolean insert(DocSaverBuilder docSaverBuilder) {
		try {
			String content = docSaverBuilder.getContent();
			JSONObject object = JSONObject.parseObject(content);
			//判断索引是否存在,不存在创建索引
			String suffix = docSaverBuilder.getSuffixer().createAliasName(object);
			String index = docSaverBuilder.getIndex()+suffix;
			String mappingPath = docSaverBuilder.getMappingPath();
			if(StringUtils.isNotEmpty(suffix)){
				esIndexUtils.checkAndCreateIndex(index, mappingPath.replaceAll("\\{SUFFIX}", suffix), docSaverBuilder.getSuffixer());
			}

			//判断id是否存在，不存在则生成uuid
			String id = object.getString(CommonColumn.ID);
			if(StringUtils.isNotEmpty(id)){
		        IndexRequest request = new IndexRequest(index).id(id).source(object);
				esBulkProcessor.addIndexRequest(request);
			}else{
				String uuid= IdGen.uuid();
				object.put(CommonColumn.ID, IdGen.uuid());
		        IndexRequest request = new IndexRequest(index).id(uuid).source(object);
				esBulkProcessor.addIndexRequest(request);
			}
		} catch (Exception e) {
			logger.error("save error {} ", ExceptionUtil.getRootCause(e));
		}
		return true;
	}


	/**
	 * 索引数据更新
	 * @param docSaverBuilder
	 */
	@Override
	public boolean update(DocSaverBuilder docSaverBuilder) {
		boolean flag=false;
		try {
			String content = docSaverBuilder.getContent();
			String index = docSaverBuilder.getIndex();
			JSONObject object = JSONObject.parseObject(content);
			String id = object.getString(CommonColumn.ID);

			UpdateRequest request = new UpdateRequest(index, id)
	                .doc(object)
	                .docAsUpsert(true);
			RestStatus status = client.update(request, RequestOptions.DEFAULT).status();
	        if (status.name().contains("FAIL")) {
	        	logger.error("ERROR: \n{}", status.toString());
	        }else{
	        	flag=true;
	        }
		} catch (Exception e) {
			logger.info("update error{} ", ExceptionUtil.getRootCause(e));
		}
        return flag;
	}



	/**
	 * 索引数据删除
	 * @param docSaverBuilder
	 */
	@Override
	public boolean delete(DocSaverBuilder docSaverBuilder) {
		boolean flag=false;
		try {
			String content = docSaverBuilder.getContent();
			String index = docSaverBuilder.getIndex();
			JSONObject object = JSONObject.parseObject(content);
	        DeleteRequest request = new DeleteRequest(index , object.getString(CommonColumn.ID));
			RestStatus status = client.delete(request, RequestOptions.DEFAULT).status();
	        if (status != RestStatus.OK) {
	            logger.error("ERROR: \n{}", status.toString());
	        }else{
	        	flag=true;
	        }
		} catch (Exception e) {
			logger.info("update error{} ", ExceptionUtil.getRootCause(e));
		}
        return flag;
	}


	/**
	 * 索引数据获取
	 * @param docSaverBuilder
	 */
	@Override
	public String getById(DocSaverBuilder docSaverBuilder) {
		String result="{}";
		try {
			String content = docSaverBuilder.getContent();
			String index = docSaverBuilder.getIndex();
			JSONObject object = JSONObject.parseObject(content);
	        GetRequest request = new GetRequest(index,  object.getString(CommonColumn.ID));
	        GetResponse get = client.get(request, RequestOptions.DEFAULT);
	        if (!get.isSourceEmpty()) {
	        	result=get.getSourceAsString();
	        }
		} catch (Exception e) {
			logger.info("get error{} ", ExceptionUtil.getRootCause(e));
		}
        return result;
	}

}
